﻿using Ganweisoft.IoTCenter.Module.MediaPlatform.Models;
using IoTCenter.Utilities;
using IoTCenter.Utilities.Extensions;
using IoTCenter.Utilities.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Onvif.WebApi.Services;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Onvif.WebApi.Controllers
{
    [ApiController]
    [Route("/IoT/api/v3/VideoPlatform/Onvif")]
    [Produces("application/json")]
    [Consumes("application/json")]
    public class OnvifController : ControllerBase
    {
        private readonly IOnvifService _onvifService;
        private readonly IUdpClientService _udpClientService;
        private readonly ILogger<OnvifController> _logger;
        public OnvifController(
            ILoggerFactory loggerFactory,
            IOnvifService onvifService,
            IUdpClientService udpClientService)
        {
            _onvifService = onvifService;
            _udpClientService = udpClientService;
            _logger = loggerFactory.CreateLogger<OnvifController>();
        }

        /// <summary>
        /// 网络接口列表
        /// </summary>
        [HttpGet("network-interface/simple-list")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceList)]
        [ProducesResponseType(typeof(OperateResult<IEnumerable<NameValueObject>>), 200)]
        [AllowAnonymous]
        public async Task<OperateResult<IEnumerable<NameValueObject>>> GetNetworkInterfaceSimpleList()
        {
            var results = await _udpClientService.GetNetworkInterfaceSimpleList();

            return OperateResult.Successed(results);
        }

        /// <summary>
        /// 设备发现
        /// </summary>
        [HttpGet("device-discovery")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceList)]
        [ProducesResponseType(typeof(OperateResult<IEnumerable<OnvifDeviceListResponseModel>>), 200)]
        [AllowAnonymous]
        public async Task<OperateResult<IEnumerable<OnvifDeviceListResponseModel>>> GetDeviceDiscoverList([FromQuery] OnvifDeviceListRequestModel request)
        {
            if (request == null)
            {
                return OperateResult.Successed(Enumerable.Empty<OnvifDeviceListResponseModel>());
            }

            var results = await _onvifService.DeviceDiscoverAsync(request);

            return OperateResult.Successed(results);
        }

        /// <summary>
        ///新增onvif设备
        /// </summary>
        [HttpGet("devices")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceCreate)]
        [ProducesResponseType(typeof(OperateResult<IEnumerable<int>>), 200)]
        [AllowAnonymous]
        public async Task<OperateResult<IEnumerable<int>>> CreateDevice([FromQuery] string ip)
        {
            if (ip.IsEmpty())
            {
                ip = "192.168.0.29";
            }

            //if (request == null)
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4001, "请求参数不正确");
            //}

            //if (!request.StringLengthIsValid(out var errorMessage))
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4101, _stringLocalizer[errorMessage]);
            //}

            _logger.LogWarning($"===============设备{ip}Request Begin===============\r\n");

            var request = new OnvifDeviceCreateRequestModel()
            {
                LocalIP = "192.168.0.207",
                UserName = "admin",
                Password = "ganwei8888@",
                DeviceIps = new string[] { ip }
            };

            var result = await _onvifService.CreateDeviceAsync(request);
            if (!result.Succeeded)
            {
                return result;
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        [HttpGet("devices/ptz")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceCreate)]
        [ProducesResponseType(typeof(OperateResult), 200)]
        [AllowAnonymous]
        public async Task<OperateResult> DevicePTZ([FromQuery] string ip)
        {
            if (ip.IsEmpty())
            {
                ip = "192.168.0.29";
            }

            //if (request == null)
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4001, "请求参数不正确");
            //}

            //if (!request.StringLengthIsValid(out var errorMessage))
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4101, _stringLocalizer[errorMessage]);
            //}

            _logger.LogWarning($"===============设备{ip}Request Begin===============\r\n");

            var request = new OnvifDevicePTZControlRequestModel()
            {
                UserName = "admin",
                Password = "ganwei8888@",
                RemoteIP = ip
            };

            var result = await _onvifService.SendDevicePTZControl(request);

            return result;
        }

        [HttpGet("devices/presets")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceCreate)]
        [ProducesResponseType(typeof(OperateResult), 200)]
        [AllowAnonymous]
        public async Task<IActionResult> GetPresets([FromQuery] string ip)
        {
            if (ip.IsEmpty())
            {
                ip = "192.168.0.29";
            }

            //if (request == null)
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4001, "请求参数不正确");
            //}

            //if (!request.StringLengthIsValid(out var errorMessage))
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4101, _stringLocalizer[errorMessage]);
            //}

            _logger.LogWarning($"===============设备{ip}Request Begin===============\r\n");

            var request = new OnvifDevicePTZControlRequestModel()
            {
                UserName = "admin",
                Password = "ganwei8888@",
                RemoteIP = ip
            };

            var result = await _onvifService.GetPresets(request);

            return Ok(result);
        }

        [HttpGet("devices/presets/goto")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceCreate)]
        [ProducesResponseType(typeof(OperateResult), 200)]
        [AllowAnonymous]
        public async Task<IActionResult> GodoPresets([FromQuery] string id)
        {
            if (id.IsEmpty())
            {
                id = "1";
            }

            //if (request == null)
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4001, "请求参数不正确");
            //}

            //if (!request.StringLengthIsValid(out var errorMessage))
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4101, _stringLocalizer[errorMessage]);
            //}

            _logger.LogWarning($"===============设备{id}Request Begin===============\r\n");

            var request = new OnvifDevicePTZPresetGotoRequestModel()
            {
                UserName = "admin",
                Password = "ganwei8888@",
                RemoteIP = "192.168.0.29",
                PresetToken = id
            };

            var result = await _onvifService.GotoPresets(request);

            return Ok(result);
        }


        [HttpGet("devices/presets/set")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceCreate)]
        [ProducesResponseType(typeof(OperateResult), 200)]
        [AllowAnonymous]
        public async Task<IActionResult> SetPresets([FromQuery] string id)
        {
            if (id.IsEmpty())
            {
                id = "1";
            }

            //if (request == null)
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4001, "请求参数不正确");
            //}

            //if (!request.StringLengthIsValid(out var errorMessage))
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4101, _stringLocalizer[errorMessage]);
            //}

            _logger.LogWarning($"===============设备{id}Request Begin===============\r\n");

            var request = new OnvifDevicePTZPresetSetRequestModel()
            {
                UserName = "admin",
                Password = "ganwei8888@",
                RemoteIP = "192.168.0.29",
                PresetName = $"预置点 {id}",
                PresetToken = id
            };

            var result = await _onvifService.SetPresets(request);

            return Ok(result);
        }

        [HttpGet("devices/presets/remove")]
        // [RAMAuthorize(ApiScopes.MediaPlatform, Actions.DeviceCreate)]
        [ProducesResponseType(typeof(OperateResult), 200)]
        [AllowAnonymous]
        public async Task<IActionResult> RemovePresets([FromQuery] string id)
        {
            if (id.IsEmpty())
            {
                id = "1";
            }

            //if (request == null)
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4001, "请求参数不正确");
            //}

            //if (!request.StringLengthIsValid(out var errorMessage))
            //{
            //    return OperateResult.Failed<IEnumerable<int>>(4101, _stringLocalizer[errorMessage]);
            //}

            _logger.LogWarning($"===============设备{id}Request Begin===============\r\n");

            var request = new OnvifDevicePTZPresetRemoveRequestModel()
            {
                UserName = "admin",
                Password = "ganwei8888@",
                RemoteIP = "192.168.0.29",
                PresetToken = id
            };

            var result = await _onvifService.RemovePresets(request);

            return Ok(result);
        }

    }
}
